package com.huamoxi.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.huamoxi.entity.Role;
import com.huamoxi.entity.User;
import com.huamoxi.mapper.RoleMapper;
import com.huamoxi.mapper.UserMapper;
import com.huamoxi.utils.CacheUtil;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CustomUserDetailsServiceImpl implements UserDetailsService {

    @Resource
    UserMapper userMapper;

    @Resource
    RoleMapper roleMapper;

    @Resource
    private CacheUtil cacheUtil;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {

        User user = userMapper.findUserByAccount(account);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 设置用户的角色列表
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<Role> roles = roleMapper.findRolesByUserId(user.getId());
        if (ArrayUtil.isNotEmpty(roles)) {
            roles.forEach(role -> authorities.add(new SimpleGrantedAuthority("role_" + role.getRoleName())));
        }

        return new org.springframework.security.core.userdetails.User(user.getName(), user.getPassword(), authorities);
    }
}
